package com.cennavi.function;

import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorDouble;
import com.googlecode.aviator.runtime.type.AviatorObject;
import com.googlecode.aviator.runtime.type.AviatorRuntimeJavaType;

import java.lang.reflect.Array;
import java.util.*;

/**
 * Created by lixiaoshuang on 2018/10/16.
 */
public class ListSumFunction extends AbstractFunction {
    @Override
    /**
     * @param
     * arg1 传入的集合
     * arg2  开始位置
     * arg3  结束位置
     */
    public AviatorObject call(Map<String, Object> env, AviatorObject arg1,AviatorObject arg2,AviatorObject arg3) {
        Object value = arg1.getValue(env);
        if (value == null) {
            throw new NullPointerException("null seq");
        }

        int start = FunctionUtils.getNumberValue(arg2,env).intValue();
        int end = FunctionUtils.getNumberValue(arg3,env).intValue();

        Class<?> clazz = value.getClass();
        double result = 0.00;
        if (List.class.isAssignableFrom(clazz)) {
            List<?> list = (List<?>) value;
            Object[] a = list.toArray();
            for(int i=start;i<end;i++){
                result = result+(Double)a[i];
            }
        }else if (clazz.isArray()) {
            int length = Array.getLength(value);
            Object[] dup = (Object[]) Array.newInstance(value.getClass().getComponentType(), length);
            for (int i=start;i<end;i++) {
                result = result+(Double)Array.get(value, i);
            }
        } else{
            throw new IllegalArgumentException(arg1.desc(env) + " 请传入list集合");
        }
        return new AviatorDouble(result);
    }

    @Override
    public String getName() {
        return "listSum";
    }
}
